<template>
  <div
    class="page-popup"
    :style="{
      position: 'fixed',
      top: '0px',
      left: '0px',
      right: '0px',
      height: '60px',
      zIndex: 9999,
      backgroundColor: 'rgba(0,0,0,0.6)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'flex-end',
      padding: '0px 20px',
    }"
    v-if="showCrawl"
  >
    <Upload action="" :before-upload="handleUpload" :show-upload-list="false" :disabled="isLoading">
      <Button type="primary" long :loading="isFetching">
        开始采集 {{ isLoading ? `(${fetchCurrent}/${fetchTotal})` : '' }}
      </Button>
    </Upload>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import * as XLSX from 'xlsx';
import { getSkuList, isFetching, fetchTotal, fetchCurrent } from '../utils/index';

const local_key = 'ozon-crawl-switch-status';
const showCrawl = ref(localStorage.getItem(local_key) === '1');

let isLoading = ref(false);
function handleUpload(file) {
  isLoading.value = true;
  readWorkbook(file).then(async (workbook) => {
    let data = await readSheet(workbook);
    let skuIdList = data.map((item) => item['SKU ID']);
    const priceList = await getSkuList(skuIdList);
    downloadRes(priceList);
  });
  return false;
}
// 生成结果
function downloadRes(list) {
  const workbook = XLSX.utils.book_new();
  // 创建工作表数据
  const worksheet_data = [['SKU ID', '最低价'], ...list];
  // 将数组转换为工作表
  const worksheet = XLSX.utils.aoa_to_sheet(worksheet_data);
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  // 指定文件名
  const filename = 'SKU数据比对结果.xlsx';
  // 导出文件
  XLSX.writeFile(workbook, filename);
  isLoading.value = false;
}
// 读取数据
function readSheet(workbook) {
  return new Promise(async (resolve, reject) => {
    try {
      let sheetNames = workbook.SheetNames;
      let workSheet = workbook.Sheets[sheetNames[0]];
      var json = XLSX.utils.sheet_to_json(workSheet, {
        raw: true,
        cellText: true,
      });
      resolve(json);
    } catch (err) {
      reject(err);
    }
  });
}
// 读取workbook
function readWorkbook(file) {
  return new Promise(async (resolve, reject) => {
    let reader = new FileReader();
    reader.onload = (e) => {
      let data = e.target.result;
      let workbook = XLSX.read(data, {
        type: 'binary',
      });
      resolve(workbook);
    };
    reader.onerror = () => {
      reject(new Error('文件读取失败'));
    };
    reader.readAsBinaryString(file);
  });
}

chrome.runtime.onMessage.addListener(({ action, data }, sender, sendResponse) => {
  if (action === 'ozonCrawlStatusChange') {
    if (data) {
      showCrawl.value = true;
      localStorage.setItem(local_key, '1');
      document.body.style.paddingTop = '60px';
    } else {
      showCrawl.value = false;
      localStorage.setItem(local_key, '0');
      document.body.style.paddingTop = '0px';
    }
  }
  return true;
});
</script>
<style lang="less" scoped>
.page-popup {
  padding: 10px;
}
</style>
